package ttx.tdd.args.parse;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import ttx.tdd.args.Option;
import ttx.tdd.args.exception.ArgParseException;
import ttx.tdd.args.exception.TooManyArgumentsException;

import java.util.List;
import java.util.function.Function;

/**
 * 单个参数值的解析
 * @author
 * @date 2022-03-27
 */
public class SingleOptionParser<T> implements TypeParser<T> {

    private Function<String,T> parseFunction;

    public SingleOptionParser(Function<String,T> parseFunction) {
        this.parseFunction = parseFunction;
    }

    @Override
    public T parse(Option option, List<String> args) {
        if (CollectionUtil.isEmpty(args)) {
            return parseDefaultValueWhenGivenDefaultValue(option);
        }
        if(args.size()>1){
            throw new TooManyArgumentsException(option.cmd()+" values to much");
        }
        return parseWhenGivenArgs(option, args);
    }

    protected T parseWhenGivenArgs(Option option, List<String> args){
        return parseFunction.apply(args.get(0));
    }

    protected T parseDefaultValueWhenGivenDefaultValue(Option option){
        return parseFunction.apply(option.defaultValue());
    }
}
